package com.jp.knowledge.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.ViewGroup;

import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.BaseActivity;
import com.jp.knowledge.command.implement.FaXianShouYe;
import com.jp.knowledge.command.implement.GangWeiZhiShiPaiXu;
import com.jp.knowledge.command.implement.GangWeiZhiShiShouYe;
import com.jp.knowledge.command.implement.JinRiZhiShiShouYe;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.FirstLoginDialog;
import com.jp.knowledge.dialog.WelDialog;
import com.jp.knowledge.fragment.DailyKnowledgeFragment;
import com.jp.knowledge.fragment.FindFragment;
import com.jp.knowledge.fragment.JobknowledgeFragment;
import com.jp.knowledge.fragment.MyFragment;
import com.jp.knowledge.logic.InviteFriendsLogic;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.model.InteractDataModel;
import com.jp.knowledge.service.LatestStateService;
import com.jp.knowledge.view.maintab.MainTab1;
import com.jp.knowledge.view.maintab.MainTab2;
import com.jp.knowledge.view.maintab.MainTab3;
import com.jp.knowledge.view.maintab.MainTab4;
import com.jp.knowledge.view.maintab.MainTabView;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by 528787067@qq.com on 2017/7/21.
 */

public class HomeActivity extends BaseActivity implements MainTabView.TabSelectedListener {

	private MainTabView tabView;
	private MainTab1 tab1;
	private MainTab2 tab2;
	private MainTab3 tab3;
	private MainTab4 tab4;
	private List<Fragment> fragments;
	private DailyKnowledgeFragment dailyKnowledgeFragment;
	private JobknowledgeFragment jobknowledgeFragment;
	private FindFragment findFragment;
	private MyFragment myFragment;
	private FragmentManager fragmentManager;
	private CommDialog exitDialog;
	private PersonLogic personLogic;
	private LocalBroadCast localBroadCast;
	private LocalBroadcastManager localBroadcastManager;

	@Override
	protected int getResourceId() {
		WelDialog welDialog = new WelDialog(this);
		welDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				showHelpDialog();
			}
		});
		welDialog.show();
		return R.layout.activity_home;
	}

	@Override
	protected void init() {
		personLogic = new PersonLogic(mContext);
		initFragment();
		initTab();
		initDialog();
		initBroadcast();
		switchToFragment(getIntent().getStringExtra("command"));
		requestPremission();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		switchToFragment(intent.getStringExtra("command"));
	}

	private void switchToFragment(String command){
		if(JinRiZhiShiShouYe.class.getSimpleName().equals(command)){            // 今日知识首页
			tabView.setSelectIndex(0);
		} else if(GangWeiZhiShiShouYe.class.getSimpleName().equals(command)){   // 岗位知识首页
			tabView.setSelectIndex(1);
		} else if(GangWeiZhiShiPaiXu.class.getSimpleName().equals(command)){    // 岗位知识排序
			jobknowledgeFragment.showDragDialog();
			tabView.setSelectIndex(1);
		} else if(FaXianShouYe.class.getSimpleName().equals(command)){          // 发现首页
			tabView.setSelectIndex(2);
		}
	}

	private void initFragment(){
		fragments = new ArrayList<>();
		dailyKnowledgeFragment = new DailyKnowledgeFragment();
		jobknowledgeFragment = new JobknowledgeFragment();
		findFragment = new FindFragment();
		myFragment = new MyFragment();
		fragments.add(dailyKnowledgeFragment);
		fragments.add(jobknowledgeFragment);
		fragments.add(findFragment);
		fragments.add(myFragment);
		fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
		for(Fragment fragment : fragments) {
			fragmentTransaction.add(R.id.home_content, fragment);
			fragmentTransaction.hide(fragment);
		}
		fragmentTransaction.commit();
	}

	private void initTab(){
		tabView = (MainTabView) findViewById(R.id.home_tab);
		tabView.setTabSelectedListener(this);
		tab1 = new MainTab1(mContext);
		tab2 = new MainTab2(mContext);
		tab3 = new MainTab3(mContext);
		tab4 = new MainTab4(mContext);
		tab4.setLoginState(application.isLogin());
		tabView.addTab(tab1);
		tabView.addTab(tab2);
		tabView.addTab(tab3);
		tabView.addTab(tab4);
	}

	private void initDialog(){
		exitDialog = new CommDialog(mContext);
		exitDialog.setContent("你确定要退出荐识吗？");
		exitDialog.setRightListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				application.finish();
			}
		});
	}

	private void initBroadcast(){
		localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
			@Override
			public void done(Context context, Intent intent) {
				String action = intent.getAction();
				if(LocalBroadCast.GET_LOGIN_INFO.equals(action) || LocalBroadCast.LOGOUT_SUCCESS_BROD.equals(action)){
					tab4.setLoginState(application.isLogin());
				} else if(LocalBroadCast.GET_INTERACT_DATA_CODE.equals(action)){
					InteractDataModel dataModel = LatestStateService.getInteractDataModel();
					tab3.setMessageCount(dataModel == null ? 0 : dataModel.getCount());
					tab4.hasMessage(dataModel != null && dataModel.getSystemMsgCount() > 0);
				}
			}
		});
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(LocalBroadCast.GET_LOGIN_INFO);
		intentFilter.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
		intentFilter.addAction(LocalBroadCast.GET_INTERACT_DATA_CODE);
		localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
		localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
	}

	@Override
	protected void onDestroy() {
		localBroadcastManager.unregisterReceiver(localBroadCast);
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		exitDialog.show();
	}

	@Override
	public void onTabSelect(int oldPosition, int newPosition) {
		FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
		if(oldPosition >= 0)
			fragmentTransaction.hide(fragments.get(oldPosition));
		fragmentTransaction.show(fragments.get(newPosition));
		fragmentTransaction.commit();
		if(newPosition == 3)
			personLogic.getUserData();
	}

	@Override
	public void onTabReselect(int position) {}

	private void requestPremission(){
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			List<String> permissionList = new ArrayList<>();
			if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
				permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
			if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
				permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
			if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
				permissionList.add(Manifest.permission.READ_PHONE_STATE);
			if(permissionList.size() == 0)
				return;
			String[] permissions = new String[permissionList.size()];
			for(int i = 0; i < permissionList.size(); i++)
				permissions[i] = permissionList.get(i);
			ActivityCompat.requestPermissions(this, permissions, 0x01);
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	}

	private void showHelpDialog(){
		SharedPreferences sharedPreferences = getSharedPreferences("install", MODE_PRIVATE);
		if(sharedPreferences.getBoolean("firstTime", true)){
			final FirstLoginDialog firstLoainDialog = new FirstLoginDialog(this);
			final CommDialog remindDialog = new CommDialog(mContext);
			remindDialog.setContent("此教程可在帮助功能中打开");
			remindDialog.setRightListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					firstLoainDialog.cancel();
				}
			});
			firstLoainDialog.setClickBtnClickListener(new FirstLoginDialog.ClickBtnClickListener() {
				@Override
				public void onClickBtnClick() {
					remindDialog.show();
				}
			});
			firstLoainDialog.show();
			sharedPreferences.edit().putBoolean("firstTime", false).apply();
		}
	}
}
